// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

// 云函数入口函数
exports.main = async (event, context) => {
  switch (event.op) {
    case "add":
      return cloud.database().collection("user").add({
        data: {
          openid: event.openid,
          photo: event.photo,
          username: event.username,
          type: event.type,
          phone: event.phone
        }
      }).then(res => { return res }).catch(console.error)
    case "delete":
      return cloud.database().collection("user").doc(event.id).remove().then(res => { return res }).catch(console.error)
    case "update":
      return cloud.database().collection("user").doc(event.id).update({
        data: {
          openid: event.openid,
          photo: event.photo,
          username: event.username,
          type: event.type,
          phone: event.phone
        }
      }).then(res => { return res }).catch(console.error)
    case "select":
      switch (event.key) {
        case "u_id":
          return cloud.database().collection("user").where({
            _id: event.value
          }).get().then(res => { return res }).catch(console.error)
        case "openid":
          return cloud.database().collection("user").where({
            openid: event.value
          }).get().then(res => { return res }).catch(console.error)
      }

  }
}